package com.higgins.eventtracking.client.health;

import java.util.Date;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.higgins.eventtracking.client.EventTrackingService;
import com.higgins.eventtracking.client.EventTrackingServiceAsync;
import com.higgins.eventtracking.client.dto.HealthEventDTO;
import com.higgins.eventtracking.client.dto.HealthStatsDTO;
import com.higgins.eventtracking.client.health.components.GenericChartPanel;
import com.higgins.eventtracking.client.health.components.GenericTabInterface;

public class HealthTab extends VerticalPanel	implements GenericTabInterface		{
	private static final String SERVER_ERROR = "An error occurred while "
		+ "attempting to contact the server. Please check your network "
		+ "connection and try again.";
	private final Label currentlyIllLabel = new Label();
	private final EventTrackingServiceAsync greetingService = GWT
			.create(EventTrackingService.class);
	private boolean firstRun = true;
	private Integer tabIndex = null;
	private String tabTitle = null;
	
	@Override
	public Integer getTabIndex() {
		return tabIndex;
	}
	@Override
	public void setTabIndex(Integer index) {
		this.tabIndex = index;
	}
	@Override
	public String getTabTitle()	{
		return tabTitle;
	}
	@Override
	public void setTabTitle(String tabTitle)	{
		this.tabTitle = tabTitle;
	}

	public HealthTab()	{	}
	
	public void update()	{
		if (firstRun)	
			initialise();
	}
	public void initialise()	{
		attachComponents();
		populateFinanceStatsFields();
		firstRun = false;
	}
	
	
	public void attachComponents()	{
		final Button sendButton = new Button("Add");
		final TextBox nameField = new TextBox();
		nameField.setText("GWT User1");
		
		final ListBox healthEventTypeList = new ListBox();
		healthEventTypeList.addItem("------");
		healthEventTypeList.addItem("Dump");
		healthEventTypeList.addItem("Bloated");
		healthEventTypeList.addItem("Energy");
		healthEventTypeList.addItem("Well Being");
		healthEventTypeList.addItem("Achieve");
		healthEventTypeList.addItem("Sleep Session");
		healthEventTypeList.addItem("Ill or Injury");		
		healthEventTypeList.addItem("Positive Event");
		healthEventTypeList.addItem("Negative Event");
		
		final ListBox eventIntensityList = new ListBox();
		eventIntensityList.addItem("------");
		eventIntensityList.addItem("Significant");
		eventIntensityList.addItem("Reasonable");
		eventIntensityList.addItem("Insignificant");		
		
		final ListBox eventFrameOfMindList = new ListBox();
		eventFrameOfMindList.addItem("------");
		eventFrameOfMindList.addItem("Relationship");
		eventFrameOfMindList.addItem("Legal Career");
		eventFrameOfMindList.addItem("Build For The Future");
		eventFrameOfMindList.addItem("House Keeping");
		eventFrameOfMindList.addItem("Current Career");
		eventFrameOfMindList.addItem("Relax");
		eventFrameOfMindList.addItem("Social");
		eventFrameOfMindList.addItem("Bored");
		eventFrameOfMindList.addItem("Take Over The World");
		eventFrameOfMindList.addItem("Depressed");
		eventFrameOfMindList.addItem("Anxious");
		
		final ListBox eventStartEndList = new ListBox();
		eventStartEndList.addItem("------");
		eventStartEndList.addItem("Start");
		eventStartEndList.addItem("End");
		
		final TextBox descriptionTextBox = new TextBox();
		descriptionTextBox.setText("");
		

		final Label errorLabel = new Label();
		
		
		// We can add style names to widgets
		sendButton.addStyleName("sendButton");

		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		add(healthEventTypeList);
		add(eventIntensityList);
		add(eventFrameOfMindList);
		add(new Label("Description: "));
		add(descriptionTextBox);
		add(new Label("Start / End: "));
		add(eventStartEndList);
		add(sendButton);
		add(currentlyIllLabel);
	
		
		// Focus the cursor on the name field when the app loads
		nameField.setFocus(true);
		nameField.selectAll();

		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Remote Procedure Call");
		dialogBox.setAnimationEnabled(true);
		final Button closeButton = new Button("Close");
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		final Label textToServerLabel = new Label();
		final HTML serverResponseLabel = new HTML();
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
		dialogVPanel.add(textToServerLabel);
		dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
				sendButton.setEnabled(true);
				sendButton.setFocus(true);
			}
		});

		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler, KeyUpHandler, ChangeHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				sendTrackingEventToServer();
			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					sendTrackingEventToServer();
				}
			}

			/**
			 * Send the name from the nameField to the server and wait for a response.
			 */
			private void sendTrackingEventToServer() {
				// First, we validate the input.
				errorLabel.setText("");
				
				HealthEventDTO dto = new HealthEventDTO();
				dto.setTimestamp(new Date());
				dto.setHealthEventType(healthEventTypeList.getItemText(healthEventTypeList.getSelectedIndex()));
				dto.setHealthEventIntensity(eventIntensityList.getItemText(eventIntensityList.getSelectedIndex()));
				dto.setHealthEventFrameOfMind(eventFrameOfMindList.getItemText(eventFrameOfMindList.getSelectedIndex()));
				dto.setDescription(descriptionTextBox.getText());
				dto.setStartEnd(eventStartEndList.getItemText(eventStartEndList.getSelectedIndex()));
				
				sendButton.setEnabled(false);
				greetingService.insertHealthEvent(dto,
						new AsyncCallback<String>() {
							public void onFailure(Throwable caught) {
								// Show the RPC error message to the user
								dialogBox.setText("Remote Procedure Call - Failure");
								serverResponseLabel.addStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(SERVER_ERROR);
								dialogBox.center();
								dialogBox.setPopupPosition(0, 0);
								closeButton.setFocus(true);
							}

							public void onSuccess(String result) {
								dialogBox.setText("Remote Procedure Call");
								serverResponseLabel.removeStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(result);
								dialogBox.center();
								dialogBox.setPopupPosition(0, 0);
								closeButton.setFocus(true);
								populateFinanceStatsFields();
							}
						});
			}

			@Override
			public void onChange(ChangeEvent event) {
				eventIntensityList.setSelectedIndex(0);
			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		sendButton.addClickHandler(handler);
		nameField.addKeyUpHandler(handler);
		healthEventTypeList.addChangeHandler(handler);
	}
	private void populateFinanceStatsFields()	{
		greetingService.retrieveHealthStats(
			new AsyncCallback<HealthStatsDTO>()	{

				@Override
				public void onFailure(Throwable caught) {
					currentlyIllLabel.setText("FAILURE");
				}

				@Override
				public void onSuccess(HealthStatsDTO result) {
					currentlyIllLabel.setText(result.getIllOrInjured()?"Currently Ill":"");					
				}
		});
	}
	@Override
	public void addChartPanel(GenericChartPanel chartPanel) {
		// TODO Auto-generated method stub
		
	}
	
}
